import io
import os
import base64
import json
import pandas as pd
from utils.log_util import logger
from datetime import datetime
from fastapi import Request, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Union
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.dao.user_dao import UserDao
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.post_vo import PostPageQueryModel
from module_admin.entity.vo.user_vo import (
    AddUserModel,
    CrudUserRoleModel,
    CurrentUserModel,
    DeleteUserModel,
    EditUserModel,
    ResetUserModel,
    SelectedRoleModel,
    UserDetailModel,
    UserInfoModel,
    UserModel,
    UserPageQueryModel,
    UserPostModel,
    UserProfileModel,
    UserRoleModel,
    UserRoleQueryModel,
    UserRoleResponseModel,
)
from module_admin.service.config_service import ConfigService
from module_admin.service.dept_service import DeptService
from module_admin.service.post_service import PostService
from module_admin.service.role_service import RoleService
from utils.common_util import CamelCaseUtil, export_list2excel, get_excel_template
from utils.page_util import PageResponseModel
from utils.pwd_util import PwdUtil

from alibabacloud_ocr_api20210707.client import Client as ocr_api20210707Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ocr_api20210707 import models as ocr_api_20210707_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from PIL import Image,ImageFilter
from module_admin.entity.vo.picture_parse_vo import PictureParsePageModel, PictureParseModel,PictureModel,BatchInsertModel,PictureSaveModel,PictureDifferModel
from module_admin.entity.do.picture_parse_do import PictureParse
from module_admin.dao.picture_parse_dao import PictureParseDao
from openai import OpenAI
from config.env import AliOCRConfig,OpenAiConfig
import re


class PictureService: 
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> ocr_api20210707Client:
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            # access_key_id = "LTAI5t6sGQ8cSNhdXfcdr4vp",
            access_key_id=AliOCRConfig.ACCESS_KEY_ID,
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
           # access_key_secret="PdRIi3UTaP9aMUsXkUREYC38zcRrLI"
            access_key_secret=AliOCRConfig.ACCESS_KEY_SECRET,
        )
        # 默认公网接入地址为"ocr-api.cn-hangzhou.aliyuncs.com"，若您需要使用vpc域名访问，请确保您的ecs建立在杭州region，vpc接入地址为"ocr-api-vpc.cn-hangzhou.aliyuncs.com"
        # config.endpoint = f'ocr-api.cn-hangzhou.aliyuncs.com'
        config.endpoint = AliOCRConfig.END_POINT
        return ocr_api20210707Client(config)

    @staticmethod
    async def import_picture_services(
        request: Request,
        query_db: AsyncSession,
        file: UploadFile,
        current_user: CurrentUserModel
    ):
        # 读取上传的文件内容
        contents = await file.read()

        # 使用 Pillow 打开图片
        image = Image.open(io.BytesIO(contents))

        # 获取图片的原始尺寸
        original_width, original_height = image.size
        logger.info(f"原始图片尺寸: {original_width}x{original_height}")

        # 定义最大尺寸
        max_width, max_height = 1024, 1024

        # 计算新的尺寸，保持宽高比
        if original_width > max_width or original_height > max_height:
            ratio = min(max_width / original_width, max_height / original_height)
            new_width = int(original_width * ratio)
            new_height = int(original_height * ratio)
            image = image.resize((new_width, new_height), Image.LANCZOS)
            logger.info(f"压缩后的图片尺寸: {new_width}x{new_height}")

        # 将图片转换为字节流
        buffer = io.BytesIO()
        image.save(buffer, format='PNG')
        body_stream = buffer.getvalue()

        client = PictureService.create_client();
        # 图片url保存
        recognize_edu_question_ocr_request = ocr_api_20210707_models.RecognizeEduQuestionOcrRequest(
            body=body_stream
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            response = client.recognize_edu_question_ocr_with_options(recognize_edu_question_ocr_request, runtime)
            result = response.body;
           # 处理识别结果
            if hasattr(result, 'data'):
            # 解析Data字段中的JSON字符串，只取content
                data_json = json.loads(result.data)
                formula_content = data_json.get('content', '')
                formula_content = re.sub(r'\\+', '\\\\', formula_content)
                return CrudResponseModel(is_success=True,message="识别成功",result=formula_content)
            else:
                return CrudResponseModel(is_success=False,message="识别失败，未返回数据",result=None)
        except Exception as error:
            raise error
    @staticmethod
    async def system_picture_llmCheck(
        request: Request,
        query_db: AsyncSession,
        picture_model: PictureModel,
        current_user: CurrentUserModel
    ):

        client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
           # api_key= "sk-OHT-cEAX_RgwjHtVK2sBIw",
           # base_url=f"http://chat.app.xtu.net.cn:80/v1",
            api_key=OpenAiConfig.API_KEY,
            base_url=OpenAiConfig.BASE_URL,
        )

        # 调用模型
        response = client.chat.completions.create(
            # model="qwen25-15b",
            model=OpenAiConfig.MODEL,
            messages=[
                {"role": "system", "content": OpenAiConfig.LLM_CONTENT},
                {"role": "user", "content": picture_model.parse_content_ali}
            ]
        )

        logger.info("业务结束: %s", response)

        # 解析返回结果
        response_text = response.choices[0].message.content

        return CrudResponseModel(is_success=True,message="识别成功",result=response_text)
    
    @staticmethod
    async def differ(
        request: Request,
        query_db: AsyncSession,
        picture_model: PictureDifferModel,
        current_user: CurrentUserModel
    ):
    
        logger.info("业务开始")

        client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            api_key= OpenAiConfig.API_KEY,
            base_url=OpenAiConfig.BASE_URL,
        )

        # 调用模型
        response = client.chat.completions.create(
            # model="qwen25-15b",
            model=OpenAiConfig.MODEL,
            messages=[
                {"role": "system", "content": OpenAiConfig.DIFFER_CONTENT},
                {"role": "user", "content": picture_model.parse_content_ali},
                {"role": "user", "content": picture_model.parse_content_ai_math}
            ]
        )

        logger.info("业务结束: %s", response)

        # 解析返回结果
        response_text = response.choices[0].message.content

        return CrudResponseModel(is_success=True,message="识别成功",result=response_text)

     
    async def batch_insert_system_picture(
        request: Request,
        query_db: AsyncSession,
        add_model: BatchInsertModel,
        current_user: CurrentUserModel
    ):
        parse_models: List[PictureParseModel] = []
        if add_model.add_models:
            for save_model in add_model.add_models:
                parse_model = PictureService.create_parse_model_from_save_model(
                save_model,
                add_model.parent_name,
                add_model.root_name,
                add_model.name,
                current_user
        )
                
        parse_models.append(parse_model)
   
        picture_parses = await PictureParseDao.add_picture_parses(query_db, parse_models)
        return CrudResponseModel(is_success=True,message="新增成功",result="新增成功")
    
    
    def create_parse_model_from_save_model(save_model: PictureSaveModel, parent_name: str, root_name: str, name:str, current_user:CurrentUserModel) -> PictureParseModel:
        # 创建 PictureParse 数组
        model = PictureParseModel()
        model.parse_content_ai_math = save_model.bottom_markdown
        model.parse_content_ali = save_model.top_markdown
        model.parent_name = parent_name
        model.root_name = root_name
        model.create_by=current_user.user.user_id,
        model.dept_id=current_user.user.dept_id
        model.name = name
        model.type = save_model.type
        return model